<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		ElTable,
		ElTableColumn,
		ElPagination,
		ElInput,
		ElButton,ElMessageBox
	} from 'element-plus'
	import {
		getConsumablesCategoryTree,
	} from "@/api/ConsumablesCategory.js"
	import {
		getConsumablesStoreList,
	} from "@/api/ConsumablesStore.js"
	import {
		getConsumablesList,
		addConsumables,
		editConsumables,
		deleteConsumables,
		getConsumables,
		quickWarehouseInbound
	} from "@/api/ConsumablesList.js"
	import {
		Search,
		Plus,
    Refresh, Delete, Edit
	} from '@element-plus/icons-vue'

	// 耗材表格数据
	const tableData = ref([])
	// 耗材分类列表数据
	const CategoryListData = ref([])
	// 仓库列表数据
	const StoreListData = ref([])

	// 分页配置
	const pagination = reactive({
		page: 1,
		pageSize: 10,
		total: 0
	})

	// 搜索条件
	const searchParams = reactive({
		name: '',
		categoryId: '',
		warehouseId: ''
	})
	//加载耗材分类数据
	const getCategoryListData = async () => {
		try {
			getConsumablesCategoryTree(pagination).then(res => {
				console.log("耗材分类：", res)
				CategoryListData.value = res.data
			})

		} catch (error) {
			console.error('数据加载失败')
		}
	}
	// 加载数据
	const loadData = async () => {
		let data = {
			...searchParams,
			...pagination
		}
		try {
			getConsumablesList(data).then(res => {
				console.log("耗材列表：", res)
				tableData.value = res.data[0].mlist
				pagination.total = res.data[0].total
			})

		} catch (error) {
			console.error('数据加载失败')
		}
	}

	// 搜索重置
	const resetSearch = () => {
		searchParams.name = ''
		searchParams.categoryId = ''
    searchParams.warehouseId = ''
		loadData()
	}
	//新增
	const title = ref("新增耗材")
	const dialogVisible = ref(false)
	//显示新增弹框
	const showAdd = () => {
		title.value = "新增耗材"
		dialogVisible.value = true
	}
	const ruleFormRef = ref()
	const ruleForm = reactive({
		materialId: null,
		code: "",
		name: "",
		specification: "",
		unit: "",
		categoryId: "",
		maxStock: "",
		minStock: "",
		categoryName: "",
		remark: "",
		status: "",
		quantity: "", //数量
		warehouseId: "" //仓库id
	})
	//表单验证
	const rules = reactive({
		name: [{
			required: true,
			message: '请输入名称',
			trigger: 'blur',
		}],
		unit: [{
			required: true,
			message: '请输入单位',
			trigger: 'blur',
		}],
		categoryId: [{
			required: true,
			message: '请选择类别',
			trigger: 'change',
		}],
		status: [{
			required: true,
			message: '请选择状态',
			trigger: 'blur',
		}],
		quantity: [{
			required: true,
			message: '请输入库存',
			trigger: 'blur',
		}],
		warehouseId: [{
			required: true,
			message: '请选择仓库',
			trigger: 'blur',
		}]
	})
	//表单提交
	const submitForm = async (formEl) => {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				if (ruleForm.materialId == null) {
					//新增
					addConsumables(ruleForm).then(res => {
						ElMessage.success("新增成功")
						loadData() //加载数据
						dialogVisible.value = false //隐藏对话框
						resetForm() //重置表单
					})
				} else {
					//修改
					editConsumables(ruleForm).then(res => {
						ElMessage.success("修改成功")
						loadData() //加载数据
						dialogVisible.value = false //隐藏对话框
						resetForm() //重置表单        
					})
				}

				console.log('submit!')
			} else {
				console.log('error submit!', fields)
			}
		})
	}
	//重置表单
	const resetForm = (formEl) => {
		// 重新赋值
		Object.assign(ruleForm, {
			materialId: null,
			code: "",
			name: "",
			specification: "",
			unit: "",
			categoryId: "",
			maxStock: "",
			minStock: "",
			categoryName: "",
			remark: "",
			status: "",
			quantity: "", //数量
			warehouseId: "" //仓库id
		});
		//if (!formEl) return
		//formEl.resetFields()
	}


	//编辑
	const handleEdit = (row) => {
		console.log("row:", row)
		//显示修改对话框
		title.value = "修改耗材"
		dialogVisible.value = true
		//调用后端接口，获取数据

		getConsumables(row.materialId,row.warehouseId).then(res => {
			//ruleForm.value= res.data
			Object.assign(ruleForm, res.data); // 这里的data是上面定义的对象
			ruleForm.categoryId = res.data.categoryId + ""
		})

	}
	//删除
	const handleDelete = (row) => {
    ElMessageBox.confirm( '确定删除该耗材信息吗?',  '系统警告',    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteConsumables(row.materialId).then(res => {
        ElMessage.success("删除成功")
        loadData() //加载数据
      })
    }).catch(() => {
      console.log('取消删除')
    })


	}
	//分页
	const handleSizeChange = (val) => {
		console.log(`${val} items per page`)
		pagination.pageSize = val
		loadData()
	}
	const handleCurrentChange = (val) => {
		console.log(`current page: ${val}`)
		pagination.page = val
		loadData()
	}
	/**********快速入库************/
	const assetCount = ref(1)
	const assetCopy = async (row) => {
		//await copyAsset(row.id,assetCount.value) //快速入库
		//await assetListData()  //更新数据
		if (isNaN(assetCount.value)) {
			ElMessage.error("请输入正整数")
		} else if (assetCount.value == 0) {
			ElMessage.error("库存不能为0")
		} else if (assetCount.value < 0) {
			ElMessage.error("库存不能为负数")
		} else {
			let data = {
				materialId: row.materialId,
        warehouseId:row.warehouseId,
				quantity: assetCount.value
			}

			quickWarehouseInbound(data).then(res => {
				assetCount.value = 1;
				ElMessage.success("快速入库成功")
				loadData() //刷新数据
			}) //更新库存


		}
	}
	// 生命周期钩子
	onMounted(() => {
		loadData()
		getCategoryListData()
		getConsumablesStoreList().then(res => {
			StoreListData.value = res.data
		})
	})
</script>

<template>
	<div class="">
		<el-form :inline="true" :model="searchParams" table-layout="auto" class="demo-form-inline"
			style="margin:10px 0 0 0;">
			<el-form-item>
				<el-space>
					<el-input v-model="searchParams.name" placeholder="请输入耗材名称" style="width: 230px; "
						:prefix-icon="Search" clearable />
					<el-tree-select v-model="searchParams.categoryId" placeholder="请选择耗材类别" :data="CategoryListData"
						node-key="id" :props="{label:'name',children:'children'}" check-strictly
						:render-after-expand="false" style="width: 230px" clearable></el-tree-select>
					<el-select v-model="searchParams.warehouseId" placeholder="请选择仓库" style="width: 230px" clearable>
						<el-option v-for="st in StoreListData" :label="st.name" :value="st.id" :key="st.id" />
					</el-select>
          <el-button type="primary" :icon="Search" @click="loadData">搜索</el-button>
					<el-button type="primary" plain :icon="Refresh" @click="resetSearch">重置</el-button>
					<el-button plain type="primary" :icon="Plus" @click="showAdd">
						新增
					</el-button>
				</el-space>
			</el-form-item>
		</el-form>

		<el-table :data="tableData" table-layout="auto" height="88%">

			<el-table-column prop="code" label="耗材编码" align="left" width="180" />
			<el-table-column prop="name" label="名称" align="center"/>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag class="mx-1" type="success" v-if="scope.row.status==1">启用</el-tag>
          <el-tag class="mx-1" type="danger" v-if="scope.row.status==0">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="类别" align="center"/>
      <el-table-column prop="warehouseName" label="位置" align="center"/>
      <el-table-column prop="unit" label="单位" align="center"/>
      <el-table-column prop="specification" label="规格" align="center"/>
      <el-table-column prop="quantity" label="库存" align="center"/>
      <!--			<el-table-column prop="maxStock" label="最高库存" align="center" />-->
      <!--			<el-table-column prop="minStock" label="最低库存" align="center"  />-->
      <el-table-column label="操作" align="center" width="280">
				<template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)">
						<el-icon><el-icon-edit /></el-icon>编辑
					</el-button>
          <el-button link type="danger" :icon="Delete" @click="handleDelete(scope.row)">
                删除
          </el-button>
          <el-popover placement="right" :width="320" trigger="hover">
						<template #reference>
              <el-button link type="primary" :icon="Edit">
                快速入库
							</el-button>
						</template>
						<el-form :inline="true"
							style="display: flex;align-items: center;justify-content: space-between;font-size: 12px;">
              <el-space>耗材数量：
                <el-input placeholder="请输入数量"
									v-model="assetCount"></el-input></el-space>
							<el-button link type="primary" size="small" @click="assetCopy(scope.row)">确定</el-button>
						</el-form>
					</el-popover>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
			:total="pagination.total" layout="slot, prev, pager, next" style="margin-top: 20px"
			@size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[ 10,20, 50, 100]">
			<el-text key="1">总条数：{{ pagination.total }}</el-text>
		</el-pagination>

		<!--新增、修改对话框-->
		<el-dialog v-model="dialogVisible" :title="title" width="500" @close="resetForm">
			<el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
				<el-form-item label="名称" prop="name">
					<el-input v-model="ruleForm.name" placeholder="请输入名称" clearable />
				</el-form-item>
				<el-form-item label="规格型号" prop="specification">
					<el-input v-model="ruleForm.specification" placeholder="请输入规格型号" clearable />
				</el-form-item>
				<el-form-item label="单位" prop="unit">
					<el-input v-model="ruleForm.unit" placeholder="请输入单位" clearable />
				</el-form-item>
				<el-form-item label="类别" prop="categoryId">
					<el-tree-select v-model="ruleForm.categoryId" placeholder="请选择类别" :data="CategoryListData"
						node-key="id" :props="{label:'name',children:'children'}" check-strictly
						:render-after-expand="false" style="width: 100%" clearable></el-tree-select>
				</el-form-item>
				<el-form-item label="最高库存" prop="maxStock">
					<el-input v-model="ruleForm.maxStock" placeholder="请输入最高库存" clearable />
				</el-form-item>
				<el-form-item label="最低库存" prop="minStock">
					<el-input v-model="ruleForm.minStock" placeholder="请输入最低库存" clearable />
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-select v-model="ruleForm.status" placeholder="请选择耗材批状态" clearable>
						<el-option label="启用" value="1" />
						<el-option label="禁用" value="0" />
					</el-select>
				</el-form-item>
				<el-form-item label="仓库" prop="warehouseId">
					<el-select v-model="ruleForm.warehouseId" placeholder="请选择仓库" clearable>
						<el-option v-for="st in StoreListData" :label="st.name" :value="st.id" :key="st.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="库存" prop="quantity">
					<el-input v-model="ruleForm.quantity" placeholder="请输入库存" clearable />
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="ruleForm.remark" type="textarea" clearable />
				</el-form-item>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
					<el-button @click="resetForm(ruleFormRef)">重置</el-button>
				</div>
			</el-form>
		</el-dialog>
	</div>
</template>

<style scoped>
	.page-container {
		padding: 20px;
		background: #fff;
		border-radius: 4px;
	}

	.search-bar {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
		margin-top: 20px;
	}

	.el-pagination {
		display: flex;
		justify-content: flex-end;
		margin-top: 20px;
	}
</style>